#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
#TODO: documentation!
"""


__version__ = '$Id: __init__.py 191 2008-02-14 05:43:52Z DLacewell $'


version = '0.1'


#---- imports ----#
import os.path
import logging
import bipy
import bipy.engine

#---- requirements ----#
def _requires_pyglet_version(version):
    try:
        import pyglet
        req = [int(i) for i in version if i in '1234567890']
        have = [int(i) for i in pyglet.version if i in '1234567890']
        if tuple(req) > tuple(have):
            raise ImportError('Bipy requires Pyglet %s or later' % version)
    except ImportError:
        raise ImportError('Bipy requires Pyglet %s or later' % version)


_requires_pyglet_version('1.0')


#---- logging ----#
log_level = logging.DEBUG

def _configure_log(log_file_name=None):
    global log_level
    logging.basicConfig(format = '%(levelname)s {%(name)s} %(filename)s(%(lineno)d): %(message)s',
        datefmt = '%a, %d %b %Y %H:%M:%S',
        level = log_level)

    if log_file_name:
        #check if the log_file_name is a dir or file
        if isdir(log_file_name):
            log_file_name = os.path.join(log_file_name, '.bipy.log')

         # rotating file handler
        _log_handler = logging.handlers.RotatingFileHandler(log_file_name, mode='wb',\
            maxBytes=1024*1024, backupCount=10, encoding='utf8')
        _formatter = logging.Formatter( \
        '%(asctime)s %(levelname)s {%(name)s} %(filename)s(%(lineno)d): %(message)s', \
        '%a, %d %b %Y %H:%M:%S')

        _log_handler.setFormatter(_formatter)
        logging.getLogger().addHandler(_log_handler)

    # first log entry
    logging.getLogger('bipy').info('log configured(level: %d)' % log_level)


#---- Public Methods ----#
_initialzed = False

def init(logname=None, config=None):
    _configure_log(logname)
    # TODO: read config
    bipy._engine = bipy.engine
    bipy.engine = bipy.engine.EngineClass()
    
    global _initialzed
    _initialzed = True


def get_init():
    global _initialzed
    return _initialzed

class NotInitializedError(Exception):
    pass

def raise_init():
    global _initialzed
    if _initialzed:
        return _initialzed
    raise NotInitializedError('bipy has not been initialized yet, run bipy.init(...)')


def run(scene):
    bipy.engine.run(scene())